<%@page import="com.carple.dao.MemberDao"%>
<%@page import="com.carple.dao.RouteDao"%>
<%@page import="com.carple.dto.Board"%>
<%@page import="com.carple.dto.Route"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="com.carple.dao.BoardDao"%>
<%@page import="com.carple.dto.Member"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
	
<%! 
	BoardDao dao = new BoardDao();
	int startRow = 0;
	int pageSize = 5;
	String header = null;
	List<Board> boards = dao.getBoardList(startRow, pageSize, header);
	
	
	
	
	String getTitleString(Board board){
		StringBuilder html = new StringBuilder(256);
		for(int i = 0; i<board.getDepth();i++){
			html.append("&nbsp;&nbsp;");
		}
		
		if(board.getDepth() > 0){
			html.append("<img src='/carple/image/re.gif' />");
		}
		
		if (board.isDeleted()) {
			html.append("<span style='color:gray' ");
			html.append("onclick=\"alert('삭제된 글입니다.');\">");
			html.append(board.getTitle());
			html.append("&nbsp;(삭제된 글)");
			html.append("</span>");
		} else {
			html.append("<a href='javascript:viewboard(");
			html.append(board.getBoardNo());
			html.append(");'>");
			html.append(board.getTitle());
			html.append("</a>");
		}
		
		return html.toString();
	}


%>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <style>
      #map-canvas {
      	width: 980px;
      	height:400px;
        margin: 0 auto;
        padding: 0px
      }
    </style>
<title>같이 타면서 즐거움을 나눠요~~CarPle~~~</title>
<link rel="Stylesheet" href="/carple/styles/main.css" />
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" >
	function checkuid() {
		var	form = document.login;
		var id_pattern = new RegExp('^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/'); //아이디
		var passwd_pattern = new RegExp('[^a-zA-Z0-9]'); //비밀번호

		// 아이디 체크
		if (!form.id.value.length || id_pattern.test(form.id.value)) {
			alert("이메일 아이디로 입력해 주세요.");
			form.id.value = "";
			form.id.focus();
			return false;
		}
		// 비밀번호 체크
		if(form.pass.value=="") {
			alert("비밀번호를 정확하게 입력해 주세요.");
			form.pass.value = "";
			form.pass.focus();
			return false;
		}
		if(document.login.secure_co.value == "On"){
			form.action = "/carple/account/login.action";
		} else {
			form.action = "/carple/account/login.action";
		}
		return true;
	}
	
	function viewboard(boardno){
		<%
		//page넘버 설정
			String pageNo = request.getParameter("pageno");
			if(pageNo == null || pageNo.length() == 0){
				pageNo = "1";
			}
		%>
		<%if(session.getAttribute("loginuser")!=null){%>
			location.href = '/carple/board/view.action?boardno=' + boardno+"&pageno=<%=pageNo%>";
		<%}else{%>
			location.href = '/carple/account/loginform.action?returnuri=/carple/board/view.action?boardno='+boardno + "&pageno=<%=pageNo%>";
		<%}%>
	}
	function binid(edit){
		var id = document.getElementById("id");
		id.style.backgroundImage = edit ? 'url(http://localhost:8080/carple/image/login_bg_id.gif)' :'url(none)';
		if(edit==true){
			if(id.value!=""){
				id.style.backgroundImage = 'url(none)';
			}
		}
			
	}
	function binpass(edit){
		var pass = document.getElementById("pass");
		pass.style.backgroundImage = edit ? 'url(http://localhost:8080/carple/image/login_bg_pass.gif)' :'url(none)';
		if(edit==true){
			if(pass.value!=""){
				pass.style.backgroundImage = 'url(none)';
			}
		}
	}
	function showroute(){
		window.open("/carple/route/showroute.action","나의 루트", 
			 	"width=600, height=400, left=30, top=30, resizable=no,fullscreen=no");
	}

///////////////////////////////////showrouteall/////////////////////////////////////////////////////////////// 
<%-- <%RouteDao dao = new RouteDao(); %>  --%> 
<%-- <%ArrayList<Route> routes = dao.getRouteForNearMe();%> --%>

///////////////////////////////////showrouteall///////////////////////////////////////////////////////////////
<%

  Member member = (Member)session.getAttribute("loginuser");
  RouteDao dao2 = new RouteDao(); 
  List<Route> routes;
  Route route = null;
  int range = 1; //단위는 킬로
  System.out.println(member);
  if(member!=null){
	  route = dao2.getOrderOneByEmailId(member.getEmailId());//로그인 유저의 루트 뽑기
	  if(route  == null){
		  routes = dao2.getRouteForNearMe();
	  }else{
	  	routes = dao2.getRangeCoordinate(route.getCoordinatesX(), route.getCoordinatesY(), range);
	  }
  }
  else{
	  routes = dao2.getRouteForNearMe();
	  
  }
  
%>


    function initialize() {
    	  var mapOptions = {
    	    zoom: 10,//줌레벨 설정
    	    center: new google.maps.LatLng(37.570243, 126.980587),//초기화 맵 화면의 중심 좌표.
    	  mapTypeId: google.maps.MapTypeId.ROADMAP//맵 타입 종류 선택.(ROADMAP 등등)
    	  };
    	  var map = new google.maps.Map(document.getElementById('map-canvas'),
    	                                mapOptions);
    	  
    	  var imageURL = '/carple/image/carmain.png';
    	  var imageURLOFUser = '/carple/image/carofuser.png';

    	  setMarkers(map, mkAll, imageURL);//유저 주변 1km의 마커 or 모든 마커
    	  setMarkers(map, mkOfUser, imageURLOFUser);//유저의 마커
    	}
    
    
    
    var infowindow = new google.maps.InfoWindow({
        maxWidth: 160
      });
    var mkAll = [
				<%if(member!=null){ %>
		    		<% for (int i = routes.size() - 1; i >= 0; i--) { %>
	    				<%if(route != null && routes.get(i).getCoordinates().toString().equals(route.getCoordinates().toString())){
	    					routes.remove(i);
	    				} else { %>
	    					['route<%=i+1%>',<%=routes.get(i).getCoordinates() %>, <%=routes.get(i).getRouteOrder()%>],
	    				<% } %>
	    				
	    			<%}%>
			    <%}else{%>
			    	<% for (int i = 0; i < routes.size(); i++) { %>
			    		['route<%=i+1%>',<%=routes.get(i).getCoordinates() %>, <%=routes.get(i).getRouteOrder()%>],
			    	<%}%>
			    	
			    <%}%>
			       	];//marker좌표 배열 생성.
	
			       	var mkOfUser = null;
			       	<% if (route != null) { %>
						mkOfUser = [['routeofUser', <%=route.getCoordinates()%>,1]];
					<% } else { %>
						mkOfUser = [['routeofUser', null, 1]];
					<% } %>
					
	




	function setMarkers(map, locations, imageUrl) {
		var image = {
			url : imageUrl,
			size : new google.maps.Size(23, 20),
			origin : new google.maps.Point(0, 0),
			anchor : new google.maps.Point(11, 32)
		};
		var shape = {
			coord : [ 1, 1, 1, 20, 18, 20, 18, 1 ],
			type : 'poly'
		};
		for (var i = 0; i < locations.length; i++) {
			var beach = locations[i];
			var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
			var marker = new google.maps.Marker({
				position : myLatLng,
				map : map,
				icon : image,
				shape : shape,
				title : beach[0],
				zIndex : beach[3]
			});
		}
	}


	google.maps.event.addDomListener(window, 'load', initialize);
	/////////////////////////////////////////////showroutewll//////end///////////////////////////////////////////

</script>
</head>
<body>
	<% pageContext.include("/WEB-INF/views/include/header.jsp"); %>
	<br /><br /><br /><br /><br /><br />
	<div style="width:980px; margin:0 auto">
		<h2><%="<최신글>"%></h2>
		<%if (boards != null && boards.size() > 0) { %>
			<table border="1" style="align:right; margin:0 auto;float:left">
				<tr style="background-color:beige;height:25px">
					<th style="width:50px">번호</th>
					<th style="width:80px">머릿말</th>
					<th style="width:300px">제목</th>
					<th style="width:150px">작성자</th>
					<th style="width:100px">작성일</th>			
				</tr>
				<%for (Board board : boards){ %>
				<tr style="height:25px">
					<td style="text-align:center"><%=board.getBoardNo() %></td>
					<td style="text-align:center">
					<img style="width:20px;height:20px"
											<% if(board.getHeader().equals("driver")){%>
											src="/carple/image/image_driver.png"											
											<%}else{ %>
											src="/carple/image/image_walker.png"
											<%} %>
											/>
					</td>
					<td style="text-align:left;padding:5px">
						<%= getTitleString(board) %>
					</td>
					<td style="text-align:center"><%=board.getEmailid() %></td>
					<td style="text-align:center"><%=board.getRegDate()%></td>
				</tr>
				<%} %>
			</table>
		<%}else{ %>
			<div style='text-align:left' />등록된 게시물이 없습니다.</div>
		<%} %>
	
	
		<div id="mp_banner_r" style=" top: 100px; left: 730px; width: 250px; height: 168px;  background-color: #f7f7f7 ;border: solid 1px;float:right">
			<%-- 로그인 안한상태 --%>
			<% if (member==null) { %>
			<table width="250" border="0" cellspacing="0" cellpadding="0" >				
				<tr>
					<td	style="background-color: #f7f7f7; ">
						<!-- login -->
						<table width="234px" border="0" cellspacing="0" cellpadding="0">
							<tr>
								<td width="14" height="14"></td>
								<td></td>
							</tr>
							<tr>
								<td></td>
								<td>
									<form name="login" onSubmit="return checkuid();return false;"
										method="post">
										<table width="220" border="0" cellspacing="0"
											cellpadding="0" >
											<tr>
												<td width="160" height="30" valign="top">
													<input
													type="text" name="id" id="id" class="login_id"
													value="" tabindex="1" title="ID" onfocus="binid(false);" onblur="binid(true);"  /></td>
												<td class="txt_s1"><input type="checkbox"
													name="save_id" id="save_id" onfocus="this.blur()" 
													value="YES"><label for="save_id"
													style="padding-left: 2px;">ID저장</label></td>
											</tr>
											<tr>
												<td><input type="password" name="pass" id="pass"
													class="login_pw" onfocus="binpass(false);" onblur="binpass(true);"
													value="" tabindex="2" title="비밀번호" /></td>
												<td><input type="image"
													src="/carple/image/btn_login.gif"
													border="0" /></td>
											</tr>
											<tr>
												<td height="34" colspan="2" class="login_txt"><input
													type="checkbox" name="secure_co" id="secure_co"
													onFocus="this.blur()" value="YES" /><label
													for="secure_co" style="padding-left: 2px;">보안접속</label> 
													<a href="/carple/member/registerform.action">
													<span style="font-weight: bold;">회원가입</span></a> <a
													href="javascript:idPwSearch();" onfocus="this.blur();"
													id='a.login'><span>아이디/비번</span></a></td>
											</tr>
											<tr>
												<td colspan="2"><b>- 로그인 하시면 선택하신 서비스를 제공 받으실 수  있습니다.<br/> 
												- 아직 회원이 아니신 분께서는 회원가입을  해 주시기 바랍니다.<br/><b>
												</td>
											</tr>
										</table>
									</form>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<!-- notice -->
			</table>
			<% } else {%>
			<!-- login 한상태-->
			<table width="240" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td  width="10"></td>
					<td>
						<table width="230" border="0" cellspacing="0" cellpadding="0">
							<tr>
								<td height="40" class="issue_underline">
									<table width="100%" border="0" cellspacing="0" cellpadding="0">
										<tr>
											<td width="23">
												<% if(member.getIsOwner().equals("owner")) { %>
												<img src='/carple/image/image_driver.png' width='18' height='20' align='absmiddle' />
												<%}else{ %>
												<img src='/carple/image/image_worker.png' width='18' height='20' align='absmiddle' />
												<%} %>
											</td>
											<td>
												<a href="#" class="black" style="letter-spacing:-1px;" onFocus="this.blur()"><b><%= member.getNickName() %></b></a>
											</td>
											<td width="60" align="right"><a href="/carple/carsharing/registerform.action" onFocus="this.blur()"><img src="/carple/image/btn_myjj.png" border="0" alt="마이웨이"></a></td>
											<td width="60" align="right"><a href="/carple/account/logout.action" onFocus="this.blur()"><img src="/carple/image/btn_logout.gif" border="0" alt="로그아웃"></a></td>
										</tr>
									</table>
								</td>
							</tr>
							<tr>
								<td height="31" class="issue_underline">
									<table width="100%" border="0" cellspacing="0" cellpadding="0">
										<tr>
											<td><img style="width:103px;height:120px"
											<% MemberDao dao3 = new MemberDao(); 
												String filename = dao3.getFileName(member.getEmailId());
											%>
											<% if(filename==null) {%>
											src="/carple/image/noprofileimg.png"											
											<%}else{ %>
											src="/carple/profile/file/<%= filename %>"
											<%} %>
											/></td>
											<td width="110" class="txt_s1" style="padding-top:0px;">
											<%if(route == null){ %>
												<a href="/carple/carsharing/registerform.action" style="padding-top:3px;text-align:center">나의 경로 등록</a>
											<%}else{ %>
												<a href="javascript:showroute();" onfocus="this.blur();" style="padding-top:3px;text-align:center">나의 루트</a>
											<%} %>
											<br /><br />
											희망요금&nbsp;&nbsp;
											<% if(member.getFee()==null){ %>
											<b>0</b> 원
											<% } else {%>
											<b><%= member.getFee() %></b> 원
											<% } %>											
											<br /><br />
											<b class="txt_s1" style="padding-top:3px;">카플캐쉬&nbsp;&nbsp;<b>0</b>&nbsp;원</b>
											<br /><br />
											<a href="/carple/member/modifyform.action"><img src="/carple/image/myjjang_left_cat_12.png" border="0" alt="정보변경"></a>
											<br />
											</td>	
										</tr>
									</table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
			<%} %>	
		</div>
	</div>
	<br /><br /><br /><br /><br /><br /><br /><br /><br />
	<br /><br /><br /><br /><br />
	<div style="width:990px;margin:0 auto;">
	<b style="float:left">
	<% if (member==null){
		out.println("모든 회원님들 출발지");
	}else{
		if(route == null){
			out.println(member.getNickName()+"님은 아직  My Way 를 등록하지 않으셨습니다");
		}else{
			out.println(member.getNickName()+"님의 반경 1km내의 회원님들의 출발지");
		}
	}	
	%>
	</b>
	</div>
	<br /><br />
	<div id="map-canvas"></div>
	<br /><br />
</body>
</html>